package com.yunpai.thread;

import java.util.concurrent.locks.ReentrantLock;

/**
 * 模拟次窗口卖票案列   继承Thread 同步lock锁
 */
public class WindThreadTicketTypeTree extends Thread {
   static ReentrantLock lock = new ReentrantLock();
    static int ticket = 100;

    @Override
    public void run() {

        while (true) {
            try {
                //调用lock
                lock.lock();
                if (ticket > 0)
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                System.out.println(Thread.currentThread().getName() + "卖的是第" + ticket + "张");
                ticket--;

            } finally {
                //调用lock解锁方法
                lock.unlock();
            }
        }

    }

    public static void main(String[] args) {
        WindThreadTicketTypeTree windows1 = new WindThreadTicketTypeTree();
        WindThreadTicketTypeTree windows2 = new WindThreadTicketTypeTree();
        WindThreadTicketTypeTree windows3 = new WindThreadTicketTypeTree();
        windows1.setName("窗口一");
        windows2.setName("窗口二");
        windows3.setName("窗口三");
        windows1.start();
        windows2.start();
        windows3.start();
    }

}
